package com.demo.resourcecode.c8database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class UserServiceImpl implements UserService {

	private JdbcTemplate jdbcTemplate;

	// 设置数据源
	public void setDataSource(DataSource dataSource){
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public void save(Test t) {
		jdbcTemplate.update("insert into test(id, name) values (?, ?)", new Object[]{t.getId(), t.getName()}, new int[]{java.sql.Types.INTEGER, java.sql.Types.VARCHAR});
	}

	@Override
	public List<Test> getList() {
		return jdbcTemplate.query("SELECT * FROM test", new RowMapper<Test>(){
			@Override
			public Test mapRow(ResultSet rs, int rowNum) throws SQLException {
				Test t = new Test();
				t.setId(rs.getInt("id"));
				t.setName(rs.getString("name"));
				return t;
			}
		});
	}

	@Override
	public Test get(int id) {
		return jdbcTemplate.queryForObject("SELECT id, name FROM test where id = ?", new Object[]{id}, new int[]{java.sql.Types.INTEGER}, new RowMapper<Test>(){
			@Override
			public Test mapRow(ResultSet rs, int arg1) throws SQLException {
				Test t = new Test();
				t.setId(rs.getInt("id"));
				t.setName(rs.getString("name"));
				return t;
			}
		});
	}

}
